package com.xjrsoft.module.system.service.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.temp.SaTempUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xjrsoft.common.constant.GlobalConstant;
import com.xjrsoft.common.enums.EnabledMark;
import com.xjrsoft.common.enums.YesOrNoEnum;
import com.xjrsoft.common.exception.MyException;
import com.xjrsoft.common.utils.CryptoUtil;
import com.xjrsoft.common.utils.RedisUtil;
import com.xjrsoft.config.KeyCloakConfig;
import com.xjrsoft.config.LicenseConfig;
import com.xjrsoft.module.fabric.FabricConfig;
import com.xjrsoft.module.organization.dto.AddUserDto;
import com.xjrsoft.module.organization.entity.*;
import com.xjrsoft.module.organization.service.*;
import com.xjrsoft.module.system.dto.CreateTokenDto;
import com.xjrsoft.module.system.dto.KeycloakLoginDto;
import com.xjrsoft.module.system.dto.LoginDto;
import com.xjrsoft.module.system.dto.RegisterDto;
import com.xjrsoft.module.system.entity.LoginConfig;
import com.xjrsoft.module.system.enums.RoleTypeEnum;
import com.xjrsoft.module.system.service.ILoginConfigService;
import com.xjrsoft.module.system.service.ILoginService;
import com.xjrsoft.module.system.vo.CreateTokenVo;
import com.xjrsoft.module.system.vo.LoginVo;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: tzx
 * @Date: 2023/4/21 14:22
 */
@Service
@AllArgsConstructor
public class LoginServiceImpl implements ILoginService {

    private final IUserService userService;

    private final IUserDeptRelationService userDeptRelationService;

    private final IUserPostRelationService userPostRelationService;

    private final IPostService postService;

    private final IDepartmentService departmentService;

    private final RedisUtil redisUtil;


    private final LicenseConfig licenseConfig;

    private final ILoginConfigService loginConfigService;

    private KeyCloakConfig keyCloakConfig;

    @Resource
    private FabricConfig fabricConfig;

    @Override
    public LoginVo login(@RequestBody(required = false) LoginDto dto) {
        LoginVo result = new LoginVo();

        if (licenseConfig.getEnabled()) {
            //查出所有在线用户
            List<String> onlineUser = StpUtil.searchSessionId("", 0, Integer.MAX_VALUE, false);

            //如果已经登录人数超过授权人数  不允许登录
            if (onlineUser.size() >= licenseConfig.getLoginMax()) {
                throw new MyException("登录人数超过授权人数，无法登录，请联系管理员！");
            }
        }

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName, dto.getUserName());
        User loginUser = userService.getOne(queryWrapper);

        if (loginUser == null) {
            throw new MyException("找不到当前账户!");
        }

        List<LoginConfig> list = loginConfigService.list();
        if (list.size() == 0) {
            //如果没有，则设置为默认配置,并进行保存
            LoginConfig loginConfig = new LoginConfig();
            loginConfig.setId(1L);
            loginConfig.setMulLogin("0,1");
            loginConfig.setMutualExclusion(YesOrNoEnum.NO.getCode());
            loginConfig.setWithoutLogin(YesOrNoEnum.YES.getCode());
            loginConfig.setPasswordStrategy(YesOrNoEnum.YES.getCode());
            loginConfig.setStrategyMaxNumber(7);
            list.add(loginConfig);
            loginConfigService.save(loginConfig);
        }
        LoginConfig loginConfig = list.get(0);

        if (StrUtil.isNotBlank(loginConfig.getMulLogin())) {
            if (ObjectUtil.isNotEmpty(dto.getDeviceType()) && dto.getDeviceType() == 0 && !loginConfig.getMulLogin().contains("0")) {
                throw new MyException("当前Web端登录未授权，请联系管理员！");
            } else if (ObjectUtil.isNotEmpty(dto.getDeviceType()) && dto.getDeviceType() == 1 && !loginConfig.getMulLogin().contains("1")) {
                throw new MyException("当前APP端登录未授权，请联系管理员！");
            }
        } else {
            throw new MyException("当前Web端、app端登录未授权，请联系管理员！");
        }

        if (loginUser.getEnabledMark() == EnabledMark.DISABLED.getCode()) {
            throw new MyException("当前账号已被锁定，请联系管理员!");
        }

        //非对称加密
//        String s = CryptoUtil.rsaDecrypt(new String(Base64.getDecoder().decode(dto.getPassword())));
        //对称加密
//        String decrypt = CryptoUtil.decrypt(new String(Base64.getDecoder().decode(dto.getPassword())));

        if (!StrUtil.equals(loginUser.getPassword(), SaSecureUtil.md5BySalt(CryptoUtil.decrypt(new String(Base64.getDecoder().decode(dto.getPassword()))), GlobalConstant.SECRET_KEY))) {
            if (loginConfig.getPasswordStrategy() == YesOrNoEnum.YES.getCode()) { // 如果开启了密码策略，密码错误次数超过最大次数就锁定
                Integer number = 1;
                String value = redisUtil.get(GlobalConstant.LOGIN_ERROR_NUMBER + loginUser.getId());
                if (StrUtil.isNotBlank(value)) {
                    if (loginConfig.getStrategyMaxNumber() - 1 > Integer.valueOf(value)) {
                        redisUtil.set(GlobalConstant.LOGIN_ERROR_NUMBER + loginUser.getId(), Integer.valueOf(value) + 1);
                    } else {
                        loginUser.setEnabledMark(EnabledMark.DISABLED.getCode());
                        userService.updateById(loginUser);
                        throw new MyException("当前账号已被锁定，请联系管理员");
                    }
                } else {
                    if (loginConfig.getStrategyMaxNumber() == 1) {
                        loginUser.setEnabledMark(EnabledMark.DISABLED.getCode());
                        userService.updateById(loginUser);
                        throw new MyException("当前账号已被锁定，请联系管理员");
                    } else {
                        redisUtil.set(GlobalConstant.LOGIN_ERROR_NUMBER + loginUser.getId(), number);
                    }
                }
            }
            throw new MyException("账号或密码不正确");
        }
        //登录成功之后将对应的密码错误次数给删除掉
        redisUtil.delete(GlobalConstant.LOGIN_ERROR_NUMBER + loginUser.getId());

//        SaTokenConfig oldConfig = SaManager.getConfig();
//
//        if (loginConfig.getMutualExclusion() == YesOrNoEnum.NO.getCode()){
//            //不开启同端互斥
//            oldConfig.setIsConcurrent(true);
//        }else {
//            //开启同端互斥
//            oldConfig.setIsConcurrent(false);
//        }
//        // 注入到 SaManager 中
//        SaManager.setConfig(oldConfig);

        //此登录接口
        if (loginConfig.getWithoutLogin() == YesOrNoEnum.YES.getCode()) {//开启就设置为7天免登录
            if (ObjectUtil.isNotEmpty(dto.getDeviceType()) && dto.getDeviceType() == 1) {
                StpUtil.login(loginUser.getId(), new SaLoginModel().setDevice("APP").setTimeout(60 * 60 * 24 * 7));
            } else {//默认为PC端登录
                StpUtil.login(loginUser.getId(), new SaLoginModel().setDevice("PC").setTimeout(60 * 60 * 24 * 7));
            }
        } else {
            //此登录接口登录web端,IsLastingCookie设置为false，也就是关闭浏览器后再次打开需要重新登录
            if (ObjectUtil.isNotEmpty(dto.getDeviceType()) && dto.getDeviceType() == 1) {
                StpUtil.login(loginUser.getId(), new SaLoginModel().setDevice("APP").setIsLastingCookie(false));
            } else {//默认为PC端登录
                StpUtil.login(loginUser.getId(), new SaLoginModel().setDevice("PC").setIsLastingCookie(false));
            }
        }
//        StpUtil.login(loginUser.getId(),"PC");

        SaSession tokenSession = StpUtil.getTokenSession();

        List<UserDeptRelation> userDeptRelations = userDeptRelationService.list(Wrappers.lambdaQuery(UserDeptRelation.class)
                .eq(UserDeptRelation::getUserId, StpUtil.getLoginIdAsLong()));

        List<UserPostRelation> userPostRelations = userPostRelationService.list(Wrappers.lambdaQuery(UserPostRelation.class)
                .eq(UserPostRelation::getUserId, StpUtil.getLoginIdAsLong()));

        //获取登陆人所选择的身份缓存
        String postId = redisUtil.get(GlobalConstant.LOGIN_IDENTITY_CACHE_PREFIX + loginUser.getId());

        Post post = new Post();
        if (StrUtil.isNotBlank(postId) && !postId.equals("null")) {
            post = postService.getById(Long.valueOf(postId));
        }

        if (userPostRelations.size() > 0) {
            List<Long> postIds = userPostRelations.stream().map(UserPostRelation::getPostId).collect(Collectors.toList());

            List<Post> postList = postService.listByIds(postIds);
            if ((post == null || StrUtil.isBlank(postId)) && CollectionUtils.isNotEmpty(postList)) {
                post = postList.get(0);
            }
            tokenSession.set(GlobalConstant.LOGIN_USER_POST_INFO_KEY, post);
            tokenSession.set(GlobalConstant.LOGIN_USER_POST_LIST_KEY, postList);
            loginUser.setPostId(post.getId());

            //将登陆人所选择的身份缓存起来
            //切换身份的时候 会一起修改
            redisUtil.set(GlobalConstant.LOGIN_IDENTITY_CACHE_PREFIX + loginUser.getId(), post.getId());
        }

        if (userDeptRelations.size() > 0) {
            // 存当前用户所有部门到缓存
            List<Long> departmentIds = userDeptRelations.stream().map(UserDeptRelation::getDeptId).collect(Collectors.toList());
            List<Department> departmentList = departmentService.listByIds(departmentIds);
            tokenSession.set(GlobalConstant.LOGIN_USER_DEPT_LIST_KEY, departmentList);
            //如果此人有岗位  使用岗位的deptId  找到当前组织机构
            if (ObjectUtil.isNotNull(post) && ObjectUtil.isNotNull(post.getId())) {
                Department department = departmentService.getById(post.getDeptId());
                tokenSession.set(GlobalConstant.LOGIN_USER_DEPT_INFO_KEY, department);
                loginUser.setDepartmentId(department.getId());
            } else {

                Department department = departmentList.get(0);

                tokenSession.set(GlobalConstant.LOGIN_USER_DEPT_INFO_KEY, department);

                loginUser.setDepartmentId(department.getId());
            }

        }

        //根据登录信息  将post  和 department 信息存入用户信息中
        tokenSession.set(GlobalConstant.LOGIN_USER_INFO_KEY, loginUser);

        result.setToken(StpUtil.getTokenValue());
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String register(RegisterDto dto) {
        AddUserDto addUserDto = this.assembleUser(dto);
        boolean flag = userService.add(addUserDto);
        if (flag) {
            String txId = "";
            // 生成区块链交易
            txId = fabricConfig.cohain("org1", "add", addUserDto.getId(), JSONObject.toJSONString(dto));
            return "上链成功，交易ID:" + txId;
        }
        return "注册失败，请联系管理员";
    }

    public AddUserDto assembleUser(RegisterDto dto) {
        AddUserDto userDto = new AddUserDto();
        userDto.setUserName(dto.getUserName());
        userDto.setPassword(dto.getPassword());
        userDto.setName(dto.getName());
        userDto.setGender(dto.getGender());
        userDto.setMobile(dto.getMobile());
        userDto.setEmail(dto.getMobile() + "@139.com");
        userDto.setCode(String.valueOf(10000000 + new Random().nextInt(90000000)));
        if (null != RoleTypeEnum.of(dto.getRoleType())) {
            userDto.setDepartmentIds(Objects.requireNonNull(RoleTypeEnum.of(dto.getRoleType())).getOrgId());
            List<Long> roleList = new ArrayList<>();
            roleList.add(Objects.requireNonNull(RoleTypeEnum.of(dto.getRoleType())).getRoleId());
            userDto.setRoleIds(roleList);
        }
        return userDto;
    }

    @Override
    public CreateTokenVo createToken(CreateTokenDto dto) {
        CreateTokenVo vo = new CreateTokenVo();

        if (dto.getExpire() == -1) {
            String token = SaTempUtil.createToken(IdUtil.fastSimpleUUID() + StringPool.UNDERSCORE + GlobalConstant.SECRET_KEY, Integer.MAX_VALUE);
            vo.setToken(token);
            return vo;
        } else {
            String token = SaTempUtil.createToken(IdUtil.fastSimpleUUID() + StringPool.UNDERSCORE + GlobalConstant.SECRET_KEY, dto.getExpire());
            vo.setToken(token);
            return vo;
        }

    }

    @Override
    public LoginVo loginByKeycloak(KeycloakLoginDto dto) {

        //TODO keycloak 登陆过 解析token获取数据 做框架登录操作
        JWT jwt = JWTUtil.parseToken(dto.getToken());
        Object payload = jwt.getPayload(keyCloakConfig.getPayload());

        LoginVo result = new LoginVo();

        if (licenseConfig.getEnabled()) {
            //查出所有在线用户
            List<String> onlineUser = StpUtil.searchSessionId("", 0, Integer.MAX_VALUE, false);

            //如果已经登录人数超过授权人数  不允许登录
            if (onlineUser.size() >= licenseConfig.getLoginMax()) {
                throw new MyException("登录人数超过授权人数，无法登录，请联系管理员！");
            }
        }

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName, payload);
        User loginUser = userService.getOne(queryWrapper);

        List<LoginConfig> list = loginConfigService.list();
        if (list.size() == 0) {
            //如果没有，则设置为默认配置,并进行保存
            LoginConfig loginConfig = new LoginConfig();
            loginConfig.setId(1L);
            loginConfig.setMulLogin("0,1");
            loginConfig.setMutualExclusion(YesOrNoEnum.YES.getCode());
            loginConfig.setWithoutLogin(YesOrNoEnum.YES.getCode());
            loginConfig.setPasswordStrategy(YesOrNoEnum.YES.getCode());
            loginConfig.setStrategyMaxNumber(7);
            list.add(loginConfig);
            loginConfigService.save(loginConfig);
        }
        LoginConfig loginConfig = list.get(0);

        if (StrUtil.isNotBlank(loginConfig.getMulLogin())) {
            if (ObjectUtil.isNotEmpty(dto.getDeviceType()) && dto.getDeviceType() == 0 && !loginConfig.getMulLogin().contains("0")) {
                throw new MyException("当前Web端登录未授权，请联系管理员！");
            } else if (ObjectUtil.isNotEmpty(dto.getDeviceType()) && dto.getDeviceType() == 1 && !loginConfig.getMulLogin().contains("1")) {
                throw new MyException("当前APP端登录未授权，请联系管理员！");
            }
        } else {
            throw new MyException("当前Web端、app端登录未授权，请联系管理员！");
        }


        //此登录接口
        if (loginConfig.getWithoutLogin() == YesOrNoEnum.YES.getCode()) {//开启就设置为7天免登录
            if (ObjectUtil.isNotEmpty(dto.getDeviceType()) && dto.getDeviceType() == 1) {
                StpUtil.login(loginUser.getId(), new SaLoginModel().setDevice("APP").setTimeout(60 * 60 * 24 * 7));
            } else {//默认为PC端登录
                StpUtil.login(loginUser.getId(), new SaLoginModel().setDevice("PC").setTimeout(60 * 60 * 24 * 7));
            }
        } else {
            //此登录接口登录web端,IsLastingCookie设置为false，也就是关闭浏览器后再次打开需要重新登录
            if (ObjectUtil.isNotEmpty(dto.getDeviceType()) && dto.getDeviceType() == 1) {
                StpUtil.login(loginUser.getId(), new SaLoginModel().setDevice("APP").setIsLastingCookie(false));
            } else {//默认为PC端登录
                StpUtil.login(loginUser.getId(), new SaLoginModel().setDevice("PC").setIsLastingCookie(false));
            }
        }
//        StpUtil.login(loginUser.getId(),"PC");

        SaSession tokenSession = StpUtil.getTokenSession();

        List<UserDeptRelation> userDeptRelations = userDeptRelationService.list(Wrappers.lambdaQuery(UserDeptRelation.class)
                .eq(UserDeptRelation::getUserId, StpUtil.getLoginIdAsLong()));

        List<UserPostRelation> userPostRelations = userPostRelationService.list(Wrappers.lambdaQuery(UserPostRelation.class)
                .eq(UserPostRelation::getUserId, StpUtil.getLoginIdAsLong()));

        //获取登陆人所选择的身份缓存
        String postId = redisUtil.get(GlobalConstant.LOGIN_IDENTITY_CACHE_PREFIX + loginUser.getId());

        Post post = new Post();
        if (StrUtil.isNotBlank(postId) && !postId.equals("null")) {
            post = postService.getById(Long.valueOf(postId));
        }

        if (userPostRelations.size() > 0) {
            List<Long> postIds = userPostRelations.stream().map(UserPostRelation::getPostId).collect(Collectors.toList());

            List<Post> postList = postService.listByIds(postIds);
            if ((post == null || StrUtil.isBlank(postId)) && CollectionUtils.isNotEmpty(postList)) {
                post = postList.get(0);
            }
            tokenSession.set(GlobalConstant.LOGIN_USER_POST_INFO_KEY, post);
            tokenSession.set(GlobalConstant.LOGIN_USER_POST_LIST_KEY, postList);
            loginUser.setPostId(post.getId());

            //将登陆人所选择的身份缓存起来
            //切换身份的时候 会一起修改
            redisUtil.set(GlobalConstant.LOGIN_IDENTITY_CACHE_PREFIX + loginUser.getId(), post.getId());
        }

        if (userDeptRelations.size() > 0) {
            // 存当前用户所有部门到缓存
            List<Long> departmentIds = userDeptRelations.stream().map(UserDeptRelation::getDeptId).collect(Collectors.toList());
            List<Department> departmentList = departmentService.listByIds(departmentIds);
            tokenSession.set(GlobalConstant.LOGIN_USER_DEPT_LIST_KEY, departmentList);
            //如果此人有岗位  使用岗位的deptId  找到当前组织机构
            if (ObjectUtil.isNotNull(post.getId())) {
                Department department = departmentService.getById(post.getDeptId());
                tokenSession.set(GlobalConstant.LOGIN_USER_DEPT_INFO_KEY, department);
                loginUser.setDepartmentId(department.getId());
            } else {

                Department department = departmentList.get(0);

                tokenSession.set(GlobalConstant.LOGIN_USER_DEPT_INFO_KEY, department);

                loginUser.setDepartmentId(department.getId());
            }

        }

        //根据登录信息  将post  和 department 信息存入用户信息中
        tokenSession.set(GlobalConstant.LOGIN_USER_INFO_KEY, loginUser);

        result.setToken(StpUtil.getTokenValue());
        return result;
    }

}
